package com.cjh.mybatis12.session.defaults;


import com.cjh.mybatis12.executor.Executor;
import com.cjh.mybatis12.mapping.Environment;
import com.cjh.mybatis12.session.Configuration;
import com.cjh.mybatis12.session.SqlSession;
import com.cjh.mybatis12.session.SqlSessionFactory;
import com.cjh.mybatis12.session.TransactionIsolationLevel;
import com.cjh.mybatis12.transaction.Transaction;
import com.cjh.mybatis12.transaction.TransactionFactory;
import lombok.AllArgsConstructor;

import java.sql.SQLException;

/**
 * @Descripton
 * @Author cjh
 * @Date 2023/5/24 15:12
 */
@AllArgsConstructor
public class DefaultSqlSessionFactory implements SqlSessionFactory {

    private final Configuration configuration;


    @Override
    public SqlSession openSession() {
        Transaction tx = null;
        try {
            final Environment environment = configuration.getEnvironment();
            TransactionFactory transactionFactory = environment.getTransactionFactory();
            tx = transactionFactory.newTransaction(configuration.getEnvironment().getDataSource(),
                    TransactionIsolationLevel.READ_COMMITTED, false);
//            创建执行器
            final Executor executor = configuration.newExecutor(tx);
//            创建defaultsqlsession
            return new DefaultSqlSession(configuration, executor);
        } catch (Exception e) {
            try {
                assert tx != null;
                tx.close();
            } catch (SQLException exception) {

            }
            throw new RuntimeException("Error opening session.  Cause: " + e);

        }
    }
}
